import React, { useState, useEffect } from 'react';
import TrodeCard from './TrodeCard';
import { apiService } from '../services/api';

const TrodeList = () => {
  // Hardcoded trode list to ensure consistent order
  const TRODE_IDS = ['trode-1', 'trode-2', 'trode-3'];
  
  const [trodeData, setTrodeData] = useState({}); // { [trodeId]: trodeData }
  const [expandedTrodes, setExpandedTrodes] = useState(new Set());
  const [loading, setLoading] = useState(true);

  // Fetch individual trode data
  const fetchTrodeData = async (trodeId) => {
    try {
      const data = await apiService.getTrodeUpdate(trodeId);
      setTrodeData(prev => ({
        ...prev,
        [trodeId]: data
      }));
    } catch (error) {
      console.error(`Failed to fetch data for ${trodeId}:`, error);
      // Set default offline data for failed trodes
      setTrodeData(prev => ({
        ...prev,
        [trodeId]: {
          id: trodeId,
          address: 'localhost',
          port: trodeId === 'trode-1' ? 50051 : trodeId === 'trode-2' ? 50052 : 50053,
          online: false,
          cpu: 0,
          memory: 0,
          disk: 0,
          last_update: null,
          last_error: 'Connection failed',
          processes: [],
          users: []
        }
      }));
    }
  };

  // Fetch all trode data
  const fetchAllTrodeData = async () => {
    setLoading(true);
    await Promise.all(TRODE_IDS.map(fetchTrodeData));
    setLoading(false);
  };

  // Initial load
  useEffect(() => {
    fetchAllTrodeData();
  }, []);

  const toggleTrodeDetails = (trodeId) => {
    console.log('Toggling trode:', trodeId);
    const newExpanded = new Set();
    
    // If the clicked trode is already expanded, collapse it
    if (expandedTrodes.has(trodeId)) {
      // Just collapse the current trode (newExpanded remains empty)
    } else {
      // Expand the clicked trode and collapse all others
      newExpanded.add(trodeId);
    }
    
    console.log('New expanded trodes:', Array.from(newExpanded));
    setExpandedTrodes(newExpanded);
  };

  const renderProcesses = (processes, timestamp) => {
    if (!processes || processes.length === 0) {
      return (
        <div className="text-sm text-gray-500 text-center py-4">
          No process data available
        </div>
      );
    }

    return (
      <div className="space-y-2">
        {processes.map((proc, index) => {
          // Convert decimal values (0-1) to percentages (0-100)
          const cpuPercent = (proc.cpu || 0) * 100;
          const memPercent = (proc.mem || 0) * 100;
          
          return (
            <div key={index} className="bg-white rounded-lg p-3 shadow-sm">
              <div className="flex justify-between items-start mb-2">
                <div className="flex-1 min-w-0">
                  <div className="text-sm text-gray-900 truncate">
                    <span className="font-medium">{proc.name}</span> - {proc.cmd}
                  </div>
                </div>
              </div>
              <div className="space-y-2">
                <div className="grid grid-cols-3 gap-2 items-center w-full">
                  <span className="text-xs text-gray-500">CPU:</span>
                  <div className="w-12 bg-gray-200 rounded-full h-1.5">
                    <div 
                      className="bg-green-600 h-1.5 rounded-full" 
                      style={{ width: `${cpuPercent}%` }}
                    ></div>
                  </div>
                  <span className="text-xs">{cpuPercent.toFixed(1)}%</span>
                </div>
                <div className="grid grid-cols-3 gap-2 items-center w-full">
                  <span className="text-xs text-gray-500">Mem:</span>
                  <div className="w-12 bg-gray-200 rounded-full h-1.5">
                    <div 
                      className="bg-yellow-600 h-1.5 rounded-full" 
                      style={{ width: `${memPercent}%` }}
                    ></div>
                  </div>
                  <span className="text-xs">{memPercent.toFixed(1)}%</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  const renderUsers = (users, timestamp) => {
    if (!users || users.length === 0) {
      return (
        <div className="text-sm text-gray-500 text-center py-4">
          No user data available
        </div>
      );
    }

    return (
      <div className="space-y-2">
        {users.map((user, index) => {
          // Convert decimal values (0-1) to percentages (0-100)
          const cpuPercent = (user.cpu || 0) * 100;
          const memPercent = (user.mem || 0) * 100;
          
          return (
            <div key={index} className="bg-white rounded-lg p-3 shadow-sm">
              <div className="flex justify-between items-start mb-2">
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-gray-900">
                    {user.user}
                  </div>
                </div>
              </div>
              <div className="space-y-2">
                <div className="grid grid-cols-3 gap-2 items-center w-full">
                  <span className="text-xs text-gray-500">CPU:</span>
                  <div className="w-12 bg-gray-200 rounded-full h-1.5">
                    <div 
                      className="bg-green-600 h-1.5 rounded-full" 
                      style={{ width: `${cpuPercent}%` }}
                    ></div>
                  </div>
                  <span className="text-xs">{cpuPercent.toFixed(1)}%</span>
                </div>
                <div className="grid grid-cols-3 gap-2 items-center w-full">
                  <span className="text-xs text-gray-500">Mem:</span>
                  <div className="w-12 bg-gray-200 rounded-full h-1.5">
                    <div 
                      className="bg-yellow-600 h-1.5 rounded-full" 
                      style={{ width: `${memPercent}%` }}
                    ></div>
                  </div>
                  <span className="text-xs">{memPercent.toFixed(1)}%</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-xl font-semibold text-gray-900">Trode Status</h3>
        </div>
        <div className="text-center text-gray-500 py-8">
          Loading trodes...
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow">
      <div className="px-6 py-4 border-b border-gray-200">
        <h3 className="text-xl font-semibold text-gray-900">Trode Status</h3>
      </div>
      <div className="divide-y divide-gray-200">
        {TRODE_IDS.map((trodeId, index) => {
          const trode = trodeData[trodeId];
          if (!trode) {
            return (
              <div key={trodeId} className="px-6 py-4 text-gray-500">
                Loading {trodeId}...
              </div>
            );
          }
          
          return (
            <TrodeCard
              key={trodeId}
              trode={trode}
              isExpanded={expandedTrodes.has(trodeId)}
              onToggle={toggleTrodeDetails}
              renderProcesses={renderProcesses}
              renderUsers={renderUsers}
            />
          );
        })}
      </div>
    </div>
  );
};

export default TrodeList;